package org.example.pack1210.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mysql.jdbc.Driver;
import lombok.SneakyThrows;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

//管理链接，获取链接/关闭连接
public class DBManager {
    @SneakyThrows
    public static Connection getConnection() {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String ur1 = "jdbc:mysql://localhost:3306/2411";
        String user = "root";
        String password = "123456";
        return DriverManager.getConnection(ur1, user, password);
    }

    // 通过阿里的Druid连接数据库的方式
    public static Connection getConnection2() throws Exception {
        // 创建一个读取properties文件的类
        Properties properties = new Properties();
        // 通过类加载器的方法读取这个文件
        InputStream in = DBManager.class.getClassLoader().getResourceAsStream("druid.properties");
        // 加载这个文件
        properties.load(in);
        // 产生一个数据源
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection conn = dataSource.getConnection();
        return conn;
    }

    @SneakyThrows
    public static void closeConnection(Connection conn, PreparedStatement ps, ResultSet rs) {
        rs.close();
        ps.close();
        conn.close();
    }

    @SneakyThrows
    public static void closeConnection(Connection conn, PreparedStatement ps) {
        ps.close();
        conn.close();
    }
}
